package com.hello.syn;

/**
 * 线程安全：取钱
 * 同步块：目标更明确
 */
public class SaveTest02 {

    public static void main(String[] args) {
        Account account = new Account(100, "结婚礼金");
        SaveDrawing you = new SaveDrawing(account, 80, "你");
        SaveDrawing wife = new SaveDrawing(account, 90, "她");

        you.start();
        wife.start();
    }

}

class SaveDrawing extends Thread{
    Account account;// 取钱账户
    int DrawingMoney; // 取的钱数
    int DrawingTotal; // 口袋的钱

    public SaveDrawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.DrawingMoney = drawingMoney;
    }

    @Override
    public void run() {
       test();

    }

    public void test() {
        // 提高性能
        if (account.momey <= 0) {
            return;
        }

        synchronized (account) {
            if (account.momey - DrawingMoney < 0) {
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.momey -= DrawingMoney;
            DrawingTotal += DrawingMoney;
            System.out.println(this.getName()+"------->账户余额为："+account.momey);
            System.out.println(this.getName()+"------->口袋的钱为："+DrawingTotal);
        }
    }
}